package com.molyfun.parents.activity.myorder;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.common.ShareDialogActivity;
import com.molyfun.parents.pay.AuthResult;
import com.molyfun.parents.pay.PayResult;
import com.molyfun.parents.rest.bean.GetPayInfoResponse;
import com.molyfun.parents.rest.bean.GetWxPayInfoResponse;
import com.molyfun.parents.rest.bean.OrderDetailResponse;
import com.molyfun.parents.rest.bean.ProductDetailInfoResponse;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.uievent.UIEventListener;
import com.molyfun.parents.utils.Const;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:03/06/17.
 */
public class OrderDetailActivity extends BaseActivity implements View.OnClickListener, IWXAPIEventHandler, UIEventListener {

    @InjectView(R.id.base_title_left)
    ImageView mTitleBack;
    @InjectView(R.id.pay_wx)
    TextView mPayWx;
    @InjectView(R.id.pay_ali)
    TextView mPayAli;
    @InjectView(R.id.base_title)
    TextView mTitle;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    private OrderDetailResponse.OrderBean mOrderBean;

    private ArrayList<ProductDetailInfoResponse.ProductDetailInfoBean> mDataList;

    private IWXAPI api;

    private String mStudentId = "";
    private String mGroupId = "";//小组id，如果不为空，那么是小组的课程

    public static void startActivity(Context context, ProductDetailInfoResponse.ProductDetailInfoBean productDetailBean, String studentId) {
        ArrayList<ProductDetailInfoResponse.ProductDetailInfoBean> list = new ArrayList<>();
        list.add(productDetailBean);
        Intent intent = new Intent();
        intent.putExtra(Const.STUDENT_ID, studentId);
        intent.putParcelableArrayListExtra(Const.PRODUCT_DETAIL_BEAN_LIST, list);
        intent.setClass(context, OrderDetailActivity.class);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, ArrayList<ProductDetailInfoResponse.ProductDetailInfoBean> productDetailBeanList) {
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra(Const.PRODUCT_DETAIL_BEAN_LIST, productDetailBeanList);
        intent.setClass(context, OrderDetailActivity.class);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, OrderDetailResponse.OrderBean orderBean) {
        Intent intent = new Intent();
        intent.putExtra(Const.ORDER_BEAN, orderBean);
        intent.setClass(context, OrderDetailActivity.class);
        context.startActivity(intent);
    }


    public static void startActivity(Context context, String groupId) {
        Intent intent = new Intent();
        intent.putExtra(Const.GROUP_ID, groupId);
        intent.setClass(context, OrderDetailActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void handleUIEvent(Message msg) {
        switch (msg.what) {
            case EventDispatcherEnum.UI_EVENT_WECHAT_PAY_SUCCESS:
                finish();
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        ButterKnife.inject(this);

        mTitleBack.setOnClickListener(this);

        getSupportActionBar().setTitle("");

        mTitle.setText("购买课程");

        api = WXAPIFactory.createWXAPI(this, ShareDialogActivity.WX_APP_ID, true);
        api.registerApp(ShareDialogActivity.WX_APP_ID);

//        if(PreferencesStorageUtil.getServerMode(this) != PreferencesStorageUtil.ServerMode.OFFICAL){
//            EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
//        }

        mTitleBack.setOnClickListener(this);
        mPayWx.setOnClickListener(this);
        mPayAli.setOnClickListener(this);

        mOrderBean = getIntent().getParcelableExtra(Const.ORDER_BEAN);
        mStudentId = getIntent().getStringExtra(Const.STUDENT_ID);
        if (mOrderBean != null) {

        } else {
            mGroupId = getIntent().getStringExtra(Const.GROUP_ID);
            if(!TextUtils.isEmpty(mGroupId)){
                createTeamOrder();
            }else{
                mDataList = getIntent().getParcelableArrayListExtra(Const.PRODUCT_DETAIL_BEAN_LIST);
                if (mDataList != null && mDataList.size() > 0) {
                    //生成订单
                    createOrder(mDataList);
                }
            }
        }

        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_WECHAT_PAY_SUCCESS, this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_WECHAT_PAY_SUCCESS, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_left:
                finish();
                break;
            case R.id.pay_wx:
                payWxOrder(mOrderBean.getId());
                break;
            case R.id.pay_ali:
                payAliOrder(mOrderBean.getId());
                break;
        }
    }

    @Override
    public void onReq(BaseReq req) {
    }


    @Override
    public void onResp(BaseResp resp) {
        int result = 0;

//        Toast.makeText(this, "baseresp.getType = " + resp.getType(), Toast.LENGTH_SHORT).show();

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result = R.string.errcode_success;
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = R.string.errcode_cancel;
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = R.string.errcode_deny;
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                result = R.string.errcode_unsupported;
                break;
            default:
                result = R.string.errcode_unknown;
                break;
        }

        toast(result);
//        if(resp.errCode == BaseResp.ErrCode.ERR_OK){
//            finish();
//        }

    }

    private boolean isWeChatPayOpen = false;

    private void payWxOrder(String orderId) {
        Call<GetWxPayInfoResponse> call = MFPApplication.getInstance().getRestClient().getWxPayOrderInfo(orderId);
        call.enqueue(new Callback<GetWxPayInfoResponse>() {
            @Override
            public void onResponse(Call<GetWxPayInfoResponse> call, final Response<GetWxPayInfoResponse> response) {
                dismissProgressDialog();
                if (response.body() != null && response.body().getCode() == 200) {
                    GetWxPayInfoResponse.WeChatPayInfoBean weChatPayInfoBean = response.body().getData();
                    if (weChatPayInfoBean != null) {
                        PayReq request = new PayReq();
                        request.appId = ShareDialogActivity.WX_APP_ID;
                        request.partnerId = weChatPayInfoBean.getPartnerid();
                        request.prepayId = weChatPayInfoBean.getPrepayid();
                        request.packageValue = weChatPayInfoBean.getPackageX();
                        request.nonceStr = weChatPayInfoBean.getNoncestr();
                        request.timeStamp = weChatPayInfoBean.getTimestamp();
                        request.sign = weChatPayInfoBean.getSign();
                        api.sendReq(request);
                        isWeChatPayOpen = true;
                    }

                } else {
                    toast(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<GetWxPayInfoResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //重置
        isWeChatPayOpen = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isWeChatPayOpen) {
            finish();
        }
    }

    //支付订单
    private void payAliOrder(String orderId) {
        Call<GetPayInfoResponse> call = MFPApplication.getInstance().getRestClient().getPayOrderInfo(orderId, "alipay");
        call.enqueue(new Callback<GetPayInfoResponse>() {
            @Override
            public void onResponse(Call<GetPayInfoResponse> call, final Response<GetPayInfoResponse> response) {
                dismissProgressDialog();
                if (response.body() != null && response.body().getCode() == 200) {
                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(OrderDetailActivity.this);
                            Map<String, String> result = alipay.payV2(response.body().getData(), true);

                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();


                } else {
                    toast(response.body().getMsg());
                }

            }

            @Override
            public void onFailure(Call<GetPayInfoResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });

    }

    private void createOrder(ArrayList<ProductDetailInfoResponse.ProductDetailInfoBean> productDetailBeanArrayList) {
        showProgressDialog("正在生成订单");
        Call<OrderDetailResponse> call = MFPApplication.getInstance().getRestClient().createOrder(productDetailBeanArrayList.get(0).getId());
        call.enqueue(new Callback<OrderDetailResponse>() {
            @Override
            public void onResponse(Call<OrderDetailResponse> call, Response<OrderDetailResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (response.body().getCode() == 200 && response.body().getData() != null) {
                        mOrderBean = response.body().getData();
                    } else {
                        toast(response.body().getMsg() == null ? "" : response.body().getMsg());
                        finish();
                    }
                }
            }

            @Override
            public void onFailure(Call<OrderDetailResponse> call, Throwable t) {
                dismissProgressDialog();
                toast("网络出错");
                finish();
            }
        });
    }

    private void createTeamOrder() {
        showProgressDialog("正在生成订单");
        Call<OrderDetailResponse> call = MFPApplication.getInstance().getRestClient().createTeamOrder(mGroupId);
        call.enqueue(new Callback<OrderDetailResponse>() {
            @Override
            public void onResponse(Call<OrderDetailResponse> call, Response<OrderDetailResponse> response) {
                dismissProgressDialog();
                if (response.body() != null) {
                    if (response.body().getCode() == 200 && response.body().getData() != null) {
                        mOrderBean = response.body().getData();
                    } else {
                        toast(response.body().getMsg() == null ? "" : response.body().getMsg());
                        finish();
                    }
                }
            }

            @Override
            public void onFailure(Call<OrderDetailResponse> call, Throwable t) {
                dismissProgressDialog();
                toast("网络出错");
                finish();
            }
        });
    }



    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        toast("支付成功");
                        Message uimessage = new Message();
                        uimessage.what = EventDispatcherEnum.UI_EVENT_ALIPAY_SUCCESS;
                        MFPApplication.getInstance().getEventDispatcher().sendMessage(uimessage);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        toast("支付失败");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        toast("授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()));
                    } else {
                        // 其他状态值则为授权失败
                        toast("授权失败" + String.format("authCode:%s", authResult.getAuthCode()));

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

}
